package com.histone.heartbeat.service;

import com.histone.heartbeat.dao.ContactVerifyDao;
import com.histone.heartbeat.pojo.ContactVerifyEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;

@Service
@Slf4j
public class ContactVerifyService {
    @Autowired
    private ContactVerifyDao contactVerifyDao;

    @Autowired
    private EmailService emailService;

    public void sendEmailVerify(String email, String host, String userid) throws Exception {
        String localTime = Instant.now().toString();
        String s = "<a href='" + host + "/user/verify/email?userid=" + userid +
                "&email=" + email +
                "&verify=" + localTime +
                "'>点击验证</a>";
        emailService.sendMail(email, "邮箱验证", s);

        ContactVerifyEntity verify = new ContactVerifyEntity(userid, email, localTime);
        contactVerifyDao.save(verify);
    }

    public String verifyEmail(String email, String userid, String verify) {
        List<ContactVerifyEntity> contactVerifys = contactVerifyDao.findAllByUseridAndContact(userid, email);

        String result = contactVerifys == null ? "未查询到校验记录" : "校验不通过";

        for (ContactVerifyEntity contactVerify : contactVerifys) {
                if (contactVerify.getVerify().equalsIgnoreCase(verify)){
                    result = "success";
                }
        }

        return result;
    }
}
